/*
 * @Author: your name
 * @Date: 2024-03-25 11:56:58
 * @LastEditTime: 2024-03-25 20:04:05
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \.leetcode\904.水果成篮.cpp
 */
/*
 * @lc app=leetcode.cn id=904 lang=cpp
 *
 * [904] 水果成篮
 */

// @lc code=start
class Solution {
public:
    int totalFruit(vector<int>& fruits) {
        int len = fruits.size();
        int left = 0, right = 0;
        int maxlength = 0;
        int fruit1 = fruits[0], fruit2 = -1;// 记录水果的种类
        for(right = 0; right < len; right++){
            // 第一次记录第二种水果
            if(fruit2 == -1 && fruits[right] != fruit1){
                fruit2 = fruits[right];
                
            }
            if(fruits[right] == fruit1 || fruits[right] == fruit2){
                maxlength = (maxlength > (right-left+1))?maxlength:(right-left+1);
            }
            // 一种新的水果
            else if(fruits[right] != fruit1 && fruits[right] != fruit2){
                // 更新fruit2 和 fruit1
                fruit1 = fruits[right-1];
                fruit2 = fruits[right];
                left = right-1;
                while (1){
                    if(fruits[left] != fruit1){
                        left++;
                        break;
                    }else{
                        left--;
                    }
                }
                maxlength = (maxlength > (right-left+1))?maxlength:(right-left+1);
            }
        }
        return maxlength;
    }
};
// @lc code=end
// 类似双指针的做法，right指向的水果是已有的两种就计算最大的长度，如果是新水果，那么就要把left指向
// 的水果指向right的前一个，并while到早先遇到这个水果的位置。
// 一次过
